package com.github.rxyor.common.support.spring.context;

import java.util.Objects;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.Ordered;

/**
 *<p>
 *
 *</p>
 *
 * @author liuyang
 * @date 2019/10/5 周六 14:55:00
 * @since 1.0.0
 */
public class SpringBeanHolder implements ApplicationContextAware, Ordered {

    private static ApplicationContext context;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringBeanHolder.context = applicationContext;
    }

    public static Object getBeanObject(String beanName) {
        Objects.requireNonNull(beanName, "bean name can't be null");
        return context.getBean(beanName);
    }

    @SuppressWarnings("unchecked")
    public static <T> T getBean(String beanName) {
        Objects.requireNonNull(beanName, "bean name can't be null");
        return (T) context.getBean(beanName);
    }

    public static <T> T getBean(Class<T> c) {
        Objects.requireNonNull(c, "class type can't be null");
        return context.getBean(c);
    }

    public static <T> T getBean(String beanName, Class<T> c) {
        Objects.requireNonNull(beanName, "bean name can't be null");
        Objects.requireNonNull(c, "class type can't be null");
        return context.getBean(beanName, c);
    }

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE + 1;
    }
}
